package cn.tedu.charging.user.service.impl;


import cn.tedu.charging.common.constant.AppInfoConst;
import cn.tedu.charging.common.enums.VehicleUserBindEnum;
import cn.tedu.charging.common.pojo.param.ChargeParam;
import cn.tedu.charging.common.pojo.param.VehicleBindParam;
import cn.tedu.charging.common.pojo.po.ChargingUserInfoPO;
import cn.tedu.charging.common.pojo.po.ChargingUserVehicleBindPO;
import cn.tedu.charging.common.pojo.po.ChargingVehiclePO;
import cn.tedu.charging.common.pojo.vo.VehicleVO;
import cn.tedu.charging.user.dao.repository.UserRepository;
import cn.tedu.charging.user.dao.repository.UserVehicleRepository;
import cn.tedu.charging.user.dao.repository.VehicleRepository;

import cn.tedu.charging.user.service.UserService;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;


@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private VehicleRepository vehicleRepository;
    @Autowired
    private UserVehicleRepository userVehicleRepository;

    RestTemplate restTemplate = new RestTemplate();
    String url="https://api.weixin.qq.com/sns/jscode2session?appId={1}&secret={2}&js_code={3}&grant_type=authorization_code";

    @Override
    public Integer wxLogin(String code, String nickname) {
        String result = restTemplate.getForObject(
                url,
                String.class,
                AppInfoConst.APP_ID,
                AppInfoConst.APP_SECRET,
                code
        );
        log.info("微信登录,code={}", result);
        String openId = null;
        if(result!=null&&result.length()>0){
            //获取到了数据 解析 openid 使用fastjson
            JSONObject issuance = JSON.parseObject(result);
            //key-value session_key=si230cvouTVKco7/HtbAFA== openid=oPQKi6UKeeTdwolF3qivHOuZoNC8
            openId = (String)issuance.get("openid");
        }
        //2.判断是否可以从返回值当中 拿到openId 拿不到 抛异常RuntimeException
        if(openId==null||openId.length()==0){
            throw new RuntimeException("微信登录失败");
        }
        //3.判断数据库当中是否存在该openId
        ChargingUserInfoPO user = userRepository.getUserByOpenId(openId);
        //4.如果有user 则直接返回id 如果没有user 说明第一次登录 组织PO写入数据库 利用mybatis id回填获取id
        if(user!=null){
            return user.getId();
        }else{
            user = new ChargingUserInfoPO();
            user.setWxOpenId(openId);
            user.setNickName(nickname);
            user.setCreateTime(new Date());
            userRepository.save(user);
            return user.getId();
        }
    }

    @Override
    public VehicleVO getBindedVehicle(Integer userId) {
        //select v.* from charging_vehicle v inner join
        //charging_user_vehicle_bind b on v.id=b.vehicle_id where b.user_id=? and b.state=1
        //1.获取用户绑定的车辆
        Integer vehicleId = userVehicleRepository.getUserBindedVehicleId(userId, VehicleUserBindEnum.UNBIND.getState());
        VehicleVO vo = new VehicleVO();
        if(vehicleId!=null){
            ChargingVehiclePO po = vehicleRepository.getVehicleDetailById(vehicleId);
            if(po!=null){
                BeanUtils.copyProperties(po,vo);
                return vo;
            }
        }
        return vo;
    }

    @Override
    public Integer bindVehicle(VehicleBindParam param) {
        Integer vehicleId = userVehicleRepository.getUserBindedVehicleId(param.getUserId(), VehicleUserBindEnum.UNBIND.getState());
        if(vehicleId!=null){
            throw new RuntimeException("您已经绑定了车辆");
        }
        ChargingVehiclePO vehicle = vehicleRepository.getVehicleByLicense(param.getLicense());

        if(vehicle==null){
            vehicle = new ChargingVehiclePO();
            BeanUtils.copyProperties(param,vehicle);
            vehicle.setCreateTime(new Date());
            vehicleRepository.save(vehicle);
        }
            ChargingUserVehicleBindPO po = new ChargingUserVehicleBindPO();
            po.setUserId(param.getUserId());
            po.setVehicleId(vehicle.getId());
            po.setState(1);
            po.setUnbindTime(new Date());
            userVehicleRepository.save(po);

        return vehicle.getId();
    }

    @Override
    public void unbindVehicle(Integer userId) {
        Boolean result = userVehicleRepository.updateUserVehicleBindState(userId);
        if(!result){
            throw new RuntimeException("解绑失败");
        }
    }

    @Override
    public Double Balance(Integer userId) {
        ChargingUserInfoPO user = userRepository.getUserById(userId);
        if(user==null){
            throw new RuntimeException("用户不存在");
        }
            Double balance = userRepository.getUserBalance(userId);
        return balance;
    }

    //充值
    @Override
    public void charge(ChargeParam param) {
        userRepository.charge(param);
    }

}
